<template>
  <div class="station-info">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>站点信息</h2>
      <p>查看和管理本站点的基本信息、运营状态</p>
    </div>

    <el-row :gutter="24">
      <!-- 左侧：基本信息 -->
      <el-col :span="16">
        <!-- 站点基本信息 -->
        <el-card class="info-card" title="基本信息">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" link @click="handleEdit">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="站点名称">{{ stationInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="站点状态">
              <el-tag :type="getStationStatusType(stationInfo.status)" size="large">
                {{ getStationStatusText(stationInfo.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="站点地址" :span="2">{{ stationInfo.address }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ stationInfo.contactPhone }}</el-descriptions-item>
            <el-descriptions-item label="管理员">{{ stationInfo.managerName || '未分配' }}</el-descriptions-item>
            <el-descriptions-item label="地理坐标">
              {{ stationInfo.latitude }}, {{ stationInfo.longitude }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(stationInfo.createdAt) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 容量信息 -->
        <el-card class="info-card capacity-card" style="margin-top: 16px;">
          <template #header>
            <span>容量信息</span>
          </template>
          
          <div class="capacity-info">
            <div class="capacity-chart">
              <div class="capacity-bar">
                <div 
                  class="capacity-fill" 
                  :style="{ width: utilizationRate + '%' }"
                  :class="{ warning: utilizationRate > 80, danger: utilizationRate > 90 }"
                ></div>
              </div>
              <div class="capacity-text">{{ utilizationRate.toFixed(1) }}% 已使用</div>
            </div>
            
            <el-row :gutter="16" class="capacity-details">
              <el-col :span="8">
                <div class="detail-item">
                  <div class="detail-label">总容量</div>
                  <div class="detail-value">{{ stationInfo.capacity }}kg</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <div class="detail-label">当前负载</div>
                  <div class="detail-value">{{ stationInfo.currentLoad }}kg</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="detail-item">
                  <div class="detail-label">剩余容量</div>
                  <div class="detail-value">{{ stationInfo.capacity - stationInfo.currentLoad }}kg</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <!-- 运营统计 -->
        <el-card class="info-card" style="margin-top: 16px;">
          <template #header>
            <span>运营统计</span>
          </template>
          
          <el-row :gutter="16">
            <el-col :span="6">
              <div class="stat-box">
                <div class="stat-icon orders">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ operatingStats.totalOrders }}</div>
                  <div class="stat-text">总订单数</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-box">
                <div class="stat-icon revenue">
                  <el-icon><Money /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">¥{{ operatingStats.totalRevenue.toFixed(0) }}</div>
                  <div class="stat-text">总收益</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-box">
                <div class="stat-icon weight">
                  <el-icon><ScaleToOriginal /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ operatingStats.totalWeight }}kg</div>
                  <div class="stat-text">总重量</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-box">
                <div class="stat-icon customers">
                  <el-icon><User /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ operatingStats.customerCount }}</div>
                  <div class="stat-text">服务客户</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧：快速操作和状态 -->
      <el-col :span="8">
        <!-- 快速操作 -->
        <el-card class="info-card">
          <template #header>
            <span>快速操作</span>
          </template>
          
          <div class="quick-actions">
            <el-button type="primary" @click="handleEdit" class="action-btn">
              <el-icon><Edit /></el-icon>
              <span>编辑站点信息</span>
            </el-button>
            <el-button type="success" @click="handleRefresh" class="action-btn">
              <el-icon><Refresh /></el-icon>
              <span>刷新数据</span>
            </el-button>
            <el-button 
              :type="stationInfo.status === 'active' ? 'warning' : 'success'" 
              @click="handleToggleStatus" 
              class="action-btn"
            >
              <el-icon><Bell /></el-icon>
              <span>{{ stationInfo.status === 'active' ? '暂停服务' : '恢复服务' }}</span>
            </el-button>
            <el-button type="info" @click="handleViewAnalytics" class="action-btn">
              <el-icon><DataAnalysis /></el-icon>
              <span>查看分析报告</span>
            </el-button>
          </div>
        </el-card>

        <!-- 最近活动 -->
        <el-card class="info-card" style="margin-top: 16px;">
          <template #header>
            <span>最近活动</span>
          </template>
          
          <el-timeline class="activity-timeline">
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="formatDateTime(activity.time)"
              size="small"
            >
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-desc">{{ activity.description }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑站点信息对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑站点信息"
      width="600px"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="站点地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入站点地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="站点容量" prop="capacity">
          <el-input-number 
            v-model="editForm.capacity" 
            :min="100" 
            :step="100"
            style="width: 100%"
          />
          <span style="margin-left: 8px; color: #666;">kg</span>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number 
                v-model="editForm.latitude" 
                :precision="6"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number 
                v-model="editForm.longitude" 
                :precision="6"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitEdit">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Refresh, Bell, DataAnalysis } from '@element-plus/icons-vue'
import { stationsAPI, ordersAPI } from '@/api'
import { useStore } from 'vuex'

const store = useStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref(null)

// 站点信息
const stationInfo = reactive({
  id: null,
  name: '',
  address: '',
  latitude: 0,
  longitude: 0,
  contactPhone: '',
  capacity: 0,
  currentLoad: 0,
  managerId: null,
  managerName: '',
  status: 'active',
  createdAt: ''
})

// 运营统计
const operatingStats = reactive({
  totalOrders: 0,
  totalRevenue: 0,
  totalWeight: 0,
  customerCount: 0
})

// 最近活动
const recentActivities = ref([])

// 编辑表单
const editForm = reactive({
  name: '',
  address: '',
  contactPhone: '',
  capacity: 0,
  latitude: 0,
  longitude: 0
})

// 表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入站点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '站点名称长度在2-50个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入站点地址', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入站点容量', trigger: 'blur' },
    { type: 'number', min: 100, message: '容量不能小于100kg', trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度范围为-90到90', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { type: 'number', min: -180, max: 180, message: '经度范围为-180到180', trigger: 'blur' }
  ]
}

// 计算属性
const utilizationRate = computed(() => {
  return (stationInfo.currentLoad / stationInfo.capacity) * 100
})

// 方法
// 初始化站点信息（确保 currentStation 已加载）
const initStationInfo = async () => {
  if (!store.state.currentStation) {
    // 从 localStorage 或 Vuex 获取用户ID
    const userId = store.state.user?.id || localStorage.getItem('userId')
    
    if (!userId) {
      ElMessage.warning('请先登录')
      return
    }
    
    try {
      // 获取该用户管理的站点
      const response = await stationsAPI.getStations({ managerId: userId, page: 1, pageSize: 1 })
      
      const stations = response.list || response.data || response || []
      
      if (stations.length === 0) {
        ElMessage.warning('您还未被分配站点，请联系管理员分配站点')
        return
      }
      
      const station = stations[0]
      store.commit('SET_CURRENT_STATION', station)
    } catch (error) {
      console.error('加载用户站点失败:', error)
      ElMessage.error('加载站点信息失败')
      return
    }
  }
}

const loadStationInfo = async () => {
  loading.value = true
  try {
    await initStationInfo()
    
    if (!store.state.currentStation) {
      loading.value = false
      return
    }
    
    const stationId = store.state.currentStation.id
    
    const response = await stationsAPI.getStationById(stationId)
    
    const data = response.data || response
    Object.assign(stationInfo, data)
  } catch (error) {
    console.error('加载站点信息失败:', error)
    ElMessage.error('加载站点信息失败')
  } finally {
    loading.value = false
  }
}

const loadOperatingStats = async () => {
  try {
    await initStationInfo()
    
    if (!store.state.currentStation) {
      return
    }
    
    const stationId = store.state.currentStation.id
    
    const response = await stationsAPI.getStationLoadStats(stationId)
    
    const data = response.data || response
    Object.assign(operatingStats, data)
  } catch (error) {
    console.error('加载运营统计失败:', error)
    // 使用默认值
    operatingStats.totalOrders = 0
    operatingStats.totalRevenue = 0
    operatingStats.totalWeight = 0
    operatingStats.customerCount = 0
  }
}

const loadRecentActivities = async () => {
  try {
    await initStationInfo()
    
    if (!store.state.currentStation) {
      return
    }
    
    const stationId = store.state.currentStation.id
    
    // 使用按站点查询的API获取该站点的订单
    const response = await ordersAPI.getStationOrders(stationId, {
      page: 1,
      pageSize: 10
    })
    
    const orders = response.list || response.data || response || []
    
    if (orders.length === 0) {
      recentActivities.value = []
      return
    }
    
    // 转换为活动记录（只取最近4条）
    recentActivities.value = orders.slice(0, 4).map(order => {
      let title = ''
      let description = ''
      
      switch (order.status) {
        case 'completed':
          title = `订单 ${order.orderNo} 已完成`
          description = `客户${order.customerName || ''}的回收订单处理完成，收益 ¥${order.totalAmount || 0}`
          break
        case 'in_progress':
          title = `订单 ${order.orderNo} 处理中`
          description = `正在处理客户${order.customerName || ''}的回收订单`
          break
        case 'confirmed':
          title = `订单 ${order.orderNo} 已确认`
          description = `订单已分配到本站点，等待处理`
          break
        case 'pending':
          title = `新订单 ${order.orderNo}`
          description = `待确认的新订单`
          break
        case 'cancelled':
          title = `订单 ${order.orderNo} 已取消`
          description = order.notes || '订单已取消'
          break
        default:
          title = `订单 ${order.orderNo}`
          description = '订单更新'
      }
      
      return {
        id: order.id,
        title: title,
        description: description,
        time: order.updatedAt || order.createdAt
      }
    })
  } catch (error) {
    console.error('加载最近活动失败:', error)
    recentActivities.value = []
  }
}

const handleEdit = () => {
  Object.assign(editForm, stationInfo)
  editDialogVisible.value = true
}

const handleRefresh = () => {
  loadStationInfo()
  loadOperatingStats()
  loadRecentActivities()
  ElMessage.success('数据已刷新')
}

const handleToggleStatus = async () => {
  const newStatus = stationInfo.status === 'active' ? 'closed' : 'active'
  const action = newStatus === 'active' ? '恢复服务' : '暂停服务'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}吗？这将影响订单分配和处理。`,
      `确认${action}`,
      {
        type: 'warning'
      }
    )
    
    await stationsAPI.updateStationStatus(stationInfo.id, newStatus)
    stationInfo.status = newStatus
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleViewAnalytics = () => {
  ElMessage.info('分析报告功能开发中...')
}

const submitEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    submitting.value = true
    
    await stationsAPI.updateStation(stationInfo.id, editForm)
    Object.assign(stationInfo, editForm)
    
    ElMessage.success('站点信息更新成功')
    editDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('更新失败')
    }
  } finally {
    submitting.value = false
  }
}

const getStationStatusType = (status) => {
  const statusTypes = {
    active: 'success',
    busy: 'warning',
    closed: 'danger'
  }
  return statusTypes[status] || 'info'
}

const getStationStatusText = (status) => {
  const statusTexts = {
    active: '正常运营',
    busy: '繁忙',
    closed: '关闭'
  }
  return statusTexts[status] || '未知'
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadStationInfo()
  loadOperatingStats()
  loadRecentActivities()
})
</script>

<style scoped>
.station-info {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.info-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.capacity-info {
  padding: 16px 0;
}

.capacity-chart {
  margin-bottom: 24px;
}

.capacity-bar {
  width: 100%;
  height: 20px;
  background: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
}

.capacity-fill {
  height: 100%;
  background: #67c23a;
  transition: width 0.3s ease;
  border-radius: 10px;
}

.capacity-fill.warning {
  background: #e6a23c;
}

.capacity-fill.danger {
  background: #f56c6c;
}

.capacity-text {
  text-align: center;
  margin-top: 8px;
  font-weight: 500;
  color: #333;
}

.capacity-details {
  margin-top: 16px;
}

.detail-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.detail-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.detail-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-box {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 12px;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 20px;
  color: white;
}

.stat-icon.orders {
  background: #409eff;
}

.stat-icon.revenue {
  background: #67c23a;
}

.stat-icon.weight {
  background: #e6a23c;
}

.stat-icon.customers {
  background: #f56c6c;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.stat-text {
  font-size: 12px;
  color: #666;
}

.quick-actions {
  padding: 8px 0;
  display: flex;
  flex-direction: column;
}

.action-btn {
  width: 100%;
  margin-bottom: 12px;
  height: 40px;
}

.action-btn :deep(.el-icon) {
  margin-right: 6px;
  font-size: 16px;
}

.action-btn:last-child {
  margin-bottom: 0;
}

.activity-timeline {
  padding: 8px 0;
}

.activity-content {
  padding-left: 12px;
}

.activity-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 12px;
  color: #666;
}
</style>



